import { BrowserWindow, ipcMain, IpcMainEvent, shell, app } from 'electron'
import { createConfigWindow } from '../config'

export function registerIpcMain(win: BrowserWindow) {
  ipcMain.on('hideWindow', () => {
    if (win) {
      win.hide()
    }
  })
}

export function ignoreMouseEvent(win: BrowserWindow): void {
  ipcMain.on(
    'ignoreMouseEvent',
    (_event: IpcMainEvent, ignore: boolean, options: { forward: boolean } = { forward: true }) => {
      win.setIgnoreMouseEvents(ignore, options)
    }
  )
}

export function openConfigWindow() {
  ipcMain.on('openConfigWindow', () => {
    createConfigWindow()
  })
}

//快速打开网页
export function openUrl() {
  ipcMain.on('openUrl', (_event: IpcMainEvent, url: string) => {
    if (url.startsWith('http')) {
      shell.openExternal(url)
    }
  })
}

//设置窗口大小
export function setWindowSize(win: BrowserWindow) {
  ipcMain.on('setWindowSize', (_event: IpcMainEvent, height: number) => {
    // 获取当前窗口的大小
    const [currentWidth] = win.getSize()
    win.setBounds({ width: currentWidth, height: height }) // 动态调整窗口大小
  })
}
export function setAutoLaunch() {
  ipcMain.on('setAutoLaunch', (_event: IpcMainEvent, enable: boolean) => {
    console.log(enable, 'enable')
    app.setLoginItemSettings({
      openAtLogin: enable // 用户选择是否开启
    })
  })
}

// 检查当前开机自启动状态
export function isAutoLaunchEnabled(win: BrowserWindow) {
  win.webContents.once('did-finish-load', () => {
    const settings = app.getLoginItemSettings()
    console.log(settings.openAtLogin, 'settings')
    // 发送开机自启动设置到渲染进程
    win.webContents.send('autoLaunch', settings.openAtLogin)
  })
}
